<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="优惠金额" prop="couponPrice">
        <el-input
          v-model="queryParams.couponPrice"
          placeholder="请输入优惠金额"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="起始日期" prop="couponTimeStart">
        <el-date-picker
          clearable
          v-model="queryParams.couponTimeStart"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择优惠券起始日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="折扣率" prop="couponDiscount">
        <el-input
          v-model="queryParams.couponDiscount"
          placeholder="请输入优惠券折扣率"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="最低消费多少金额可用优惠券" prop="couponMin">
        <el-input
          v-model="queryParams.couponMin"
          placeholder="请输入最低消费多少金额可用优惠券"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="截止日期" prop="couponTimeEnd">
        <el-date-picker
          clearable
          v-model="queryParams.couponTimeEnd"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择优惠券截止日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="积分换购" prop="couponTrade">
        <el-input
          v-model="queryParams.couponTrade"
          placeholder="请输入积分换购"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="图片" prop="couponPic">
        <el-input
          v-model="queryParams.couponPic"
          placeholder="请输入优惠券图片"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="店铺" prop="shopName">
        <el-input
          v-model="queryParams.shopName"
          placeholder="请输入店铺名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['shop:coupon:add']"
          >新增</el-button
        >
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['shop:coupon:edit']"
          >修改</el-button
        >
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['shop:coupon:remove']"
          >删除</el-button
        >
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['shop:coupon:export']"
          >导出</el-button
        >
      </el-col> -->
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="couponList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="couponId" />
      <el-table-column label="优惠金额" align="center" prop="couponPrice" />
      <el-table-column
        label="起始日期"
        align="center"
        prop="couponTimeStart"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.couponTimeStart, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="类型" align="center" prop="couponType" />
      <el-table-column
        label="折扣率"
        align="center"
        prop="couponDiscount"
      />
      <el-table-column
        label="最低消费金额"
        align="center"
        prop="couponMin"
      />
      <el-table-column
        label="截止日期"
        align="center"
        prop="couponTimeEnd"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.couponTimeEnd, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="积分换购" align="center" prop="couponTrade" />
      <el-table-column label="图片" align="center" prop="couponPic">
        <template #default="scope">
          <img
            v-if="scope.row.couponPic"
            :src="scope.row.couponPic"
            style="width: 100px; height: 100px"
          />
        </template>
      </el-table-column>
      <el-table-column label="店铺" align="center" prop="shopName" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="router.push({path:'/shopDetail',query:{couponId:scope.row.couponId,shopName:scope.row.shopName}})"
            v-hasPermi="['shop:coupon:edit']"
            >去使用</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['shop:coupon:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改优惠券对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="couponRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="优惠金额" prop="couponPrice">
          <el-input v-model="form.couponPrice" placeholder="请输入优惠金额" />
        </el-form-item>
        <el-form-item label="优惠券起始日期" prop="couponTimeStart">
          <el-date-picker
            clearable
            v-model="form.couponTimeStart"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择优惠券起始日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="优惠券折扣率" prop="couponDiscount">
          <el-input
            v-model="form.couponDiscount"
            placeholder="请输入优惠券折扣率"
          />
        </el-form-item>
        <el-form-item label="最低消费金额" prop="couponMin">
          <el-input
            v-model="form.couponMin"
            placeholder="请输入最低消费多少金额可用优惠券"
          />
        </el-form-item>
        <el-form-item label="优惠券截止日期" prop="couponTimeEnd">
          <el-date-picker
            clearable
            v-model="form.couponTimeEnd"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择优惠券截止日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="积分换购" prop="couponTrade">
          <el-input v-model="form.couponTrade" placeholder="请输入积分换购" />
        </el-form-item>
        <el-form-item label="优惠券图片" prop="couponPic">
          <el-input v-model="form.couponPic" placeholder="请输入优惠券图片" />
        </el-form-item>
        <el-form-item label="店铺识别码" prop="shopId">
          <el-input v-model="form.shopId" placeholder="请输入店铺识别码" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Coupon">
import {
  listCoupon,
  getCoupon,
  delCoupon,
  addCoupon,
  updateCoupon,
} from "@/api/shop/coupon";
import { listShop } from "@/api/shop/shop";
import useUserStore from "@/store/modules/user";
import { getCurrentInstance, ref, reactive, watch, toRefs } from "vue";
import { useRouter } from "vue-router";
const router = useRouter();
const { proxy } = getCurrentInstance();
const userStore = useUserStore();
const couponList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    couponPrice: null,
    couponTimeStart: null,
    couponType: null,
    couponDiscount: null,
    couponMin: null,
    couponTimeEnd: null,
    couponTrade: null,
    couponPic: null,
    shopName: null,
  },
  rules: {
    couponPrice: [
      { required: true, message: "优惠金额不能为空", trigger: "blur" },
    ],
    couponTimeStart: [
      { required: true, message: "优惠券起始日期不能为空", trigger: "blur" },
    ],
    couponType: [
      {
        required: true,
        message:
          "优惠券类型(0-折扣优惠 1-满减优惠 2-积分换购 3-会员专享)不能为空",
        trigger: "change",
      },
    ],
    couponDiscount: [
      { required: true, message: "优惠券折扣率不能为空", trigger: "blur" },
    ],
    couponMin: [
      {
        required: true,
        message: "最低消费多少金额可用优惠券不能为空",
        trigger: "blur",
      },
    ],
    couponTimeEnd: [
      { required: true, message: "优惠券截止日期不能为空", trigger: "blur" },
    ],
    couponTrade: [
      { required: true, message: "积分换购不能为空", trigger: "blur" },
    ],
    couponPic: [
      { required: true, message: "优惠券图片不能为空", trigger: "blur" },
    ],
    shopName: [{ required: true, message: "店铺名不能为空", trigger: "blur" }],
  },
});

const { queryParams, queryShopParams, form, rules } = toRefs(data);

/** 查询优惠券列表 */
function getList() {
  loading.value = true;
  queryParams.value.userName = userStore.name;
  listCoupon(queryParams.value).then((response) => {
    couponList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
  // if (userStore.roles[0] == "admin") {
  //   listCoupon(queryParams.value).then(response => {
  //     couponList.value = response.rows;
  //     total.value = response.total;
  //     loading.value = false;
  //   });
  // } else if (userStore.roles[0] == "shopManager") {
  //   // 如果角色为店铺管理员
  //   queryShopParams.value.employeeName = userStore.name;
  //   // 查询出管理员管理的店铺
  //   listShop(queryShopParams.value).then(response => {
  //     queryParams.value.shopName = response.rows[0].shopName;
  //     total.value = response.total;
  //     loading.value = false;
  //     // 查询出该店铺的优惠券
  //     listCoupon(queryParams.value).then(response => {
  //       couponList.value = response.rows;
  //       total.value = response.total;
  //       loading.value = false;
  //     });
  //   }).catch(error => {
  //     console.log(error);
  //   });
  // } else if (userStore.roles[0] == "boss") {
  //   queryShopParams.value.bossName = userStore.name;
  //   // 查询旗下店铺
  //   listShop(queryShopParams.value).then(response => {
  //     // 根据旗下店铺查询出所有活动
  //     for (const shop in response.rows) {
  //       queryParams.value.shopName = response.rows[shop].shopName;
  //       listCoupon(queryParams.value).then(response => {
  //         // 遍历查询结果封装入活动查询列表
  //         response.rows.forEach(element => {
  //           couponList.value.push(element);
  //         });
  //         total.value = response.total;
  //         loading.value = false;
  //       });
  //     }
  //   }).catch(error => {
  //     console.log(error);
  //   });
  // }
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    couponId: null,
    couponPrice: null,
    couponTimeStart: null,
    couponType: null,
    couponDiscount: null,
    couponMin: null,
    couponTimeEnd: null,
    couponTrade: null,
    couponPic: null,
    shopId: null,
  };
  proxy.resetForm("couponRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.couponId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加优惠券";
}

/** 修改按钮操作 */
// function handleUpdate(row) {
//   // reset();
//   // const _couponId = row.couponId || ids.value;
//   // getCoupon(_couponId).then((response) => {
//   //   form.value = response.data;
//   //   open.value = true;
//   //   title.value = "修改优惠券";
//   // });
// }

/** 提交按钮 */
function submitForm() {
  proxy.$refs["couponRef"].validate((valid) => {
    if (valid) {
      if (form.value.couponId != null) {
        updateCoupon(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addCoupon(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _couponIds = row.couponId || ids.value;
  proxy.$modal
    .confirm('是否确认删除优惠券编号为"' + _couponIds + '"的数据项？')
    .then(function () {
      return delCoupon(_couponIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "shop/coupon/export",
    {
      ...queryParams.value,
    },
    `coupon_${new Date().getTime()}.xlsx`
  );
}

getList();
</script>
